package com.rickpan.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rickpan.dto.response.ImageGenerationResponse;
import com.rickpan.dto.siliconflow.SiliconFlowImageRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * 硅基流动图片生成API客户端
 *
 * 功能说明：
 * 1. 调用硅基流动的图片生成API (Kwai-Kolors/Kolors模型)
 * 2. 支持文本生成图片和图片生成图片两种模式
 * 3. 提供API Key验证功能
 * 4. 处理API调用的错误和异常情况
 *
 * 使用场景：
 * - AI助手的图片生成功能
 * - 用户通过文本描述生成图片
 * - 基于参考图片进行图片变换
 */
@Component
public class SiliconFlowImageClient {

    private static final Logger log = LoggerFactory.getLogger(SiliconFlowImageClient.class);

    /** 硅基流动图片生成API的端点URL */
    private static final String SILICONFLOW_IMAGE_API_URL = "https://api.siliconflow.cn/v1/images/generations";

    /** Spring的HTTP客户端，用于发送API请求 */
    @Autowired
    private RestTemplate restTemplate;

    /** JSON序列化/反序列化工具 */
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 发送图片生成请求到硅基流动AI
     *
     * 处理流程：
     * 1. 构建HTTP请求头（包含API Key认证）
     * 2. 将请求对象序列化为JSON
     * 3. 发送POST请求到硅基流动API
     * 4. 解析响应并返回图片URL等信息
     *
     * @param apiKey 硅基流动API密钥，用于身份验证
     * @param request 图片生成请求对象，包含提示词、尺寸、数量等参数
     * @return ImageGenerationResponse 包含生成的图片URL、生成时间等信息
     * @throws RuntimeException 当API调用失败时抛出异常
     */
    public ImageGenerationResponse generateImage(String apiKey, SiliconFlowImageRequest request) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + apiKey);
        headers.set("Content-Type", "application/json");
        headers.set("User-Agent", "RickPan/1.0");



        try {
            log.info("Processing image generation request");

            // 序列化请求为JSON
            String requestJson = objectMapper.writeValueAsString(request);

            // 发送请求
            HttpEntity<String> entity = new HttpEntity<>(requestJson, headers);
            ResponseEntity<String> response = restTemplate.exchange(
                    SILICONFLOW_IMAGE_API_URL, HttpMethod.POST, entity, String.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                String responseBody = response.getBody();
                log.info("Image generation completed successfully");

                // 解析响应
                ImageGenerationResponse imageResponse = objectMapper.readValue(responseBody, ImageGenerationResponse.class);
                return imageResponse;
            } else {
                throw new RuntimeException("硅基流动图片生成API调用失败: " + response.getStatusCode());
            }
        } catch (Exception e) {
            log.error("Error in SiliconFlow image generation request: {}", e.getMessage(), e);

            // 尝试获取更详细的错误信息
            if (e instanceof org.springframework.web.client.HttpClientErrorException) {
                org.springframework.web.client.HttpClientErrorException httpError =
                    (org.springframework.web.client.HttpClientErrorException) e;
                log.error("HTTP Error Status: {}", httpError.getStatusCode());
                log.error("HTTP Error Body: {}", httpError.getResponseBodyAsString());
            }

            // 特殊处理429错误（限额超出）
            if (e.getMessage() != null && e.getMessage().contains("429")) {
                throw new RuntimeException("API调用限额已用完，请稍后重试", e);
            }

            // 特殊处理400错误（请求参数错误）
            if (e.getMessage() != null && e.getMessage().contains("400")) {
                throw new RuntimeException("图片生成请求参数错误，请检查提示词和配置", e);
            }

            // 特殊处理500错误
            if (e.getMessage() != null && e.getMessage().contains("500")) {
                throw new RuntimeException("硅基流动服务器内部错误，请稍后重试", e);
            }

            throw new RuntimeException("硅基流动图片生成API调用失败: " + e.getMessage(), e);
        }
    }

    /**
     * 测试图片生成API Key是否有效
     * @param apiKey API密钥
     * @return 是否有效
     */
    public boolean testImageApiKey(String apiKey) {
        try {
            // 创建简单的测试请求
            SiliconFlowImageRequest testRequest = SiliconFlowImageRequest.builder()
                    .model("Kwai-Kolors/Kolors")
                    .prompt("a simple test image")
                    .imageSize("1024x1024")
                    .batchSize(1)
                    .numInferenceSteps(20)
                    .guidanceScale(7.5)
                    .build();

            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + apiKey);
            headers.set("Content-Type", "application/json");

            HttpEntity<SiliconFlowImageRequest> entity = new HttpEntity<>(testRequest, headers);
            ResponseEntity<String> response = restTemplate.exchange(
                    SILICONFLOW_IMAGE_API_URL, HttpMethod.POST, entity, String.class);

            return response.getStatusCode().is2xxSuccessful();
        } catch (Exception e) {
            log.warn("SiliconFlow Image API Key test failed: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 构建图片生成请求
     * @param prompt 提示词
     * @param imageSize 图片尺寸
     * @param batchSize 生成数量
     * @param guidanceScale 引导强度
     * @param numInferenceSteps 推理步数
     * @param referenceImage 参考图片（可选）
     * @return 硅基流动图片生成请求对象
     */
    public SiliconFlowImageRequest buildImageRequest(String prompt, String imageSize,
                                                   Integer batchSize, Double guidanceScale,
                                                   Integer numInferenceSteps, String referenceImage) {
        // 确保所有必需字段都有值
        String finalPrompt = (prompt != null && !prompt.trim().isEmpty()) ? prompt.trim() :
                "an island near sea, with seagulls, moon shining over the sea, light house, boats in the background, fish flying over the sea";
        String finalImageSize = (imageSize != null) ? imageSize : "1024x1024";
        Integer finalBatchSize = (batchSize != null && batchSize >= 1 && batchSize <= 4) ? batchSize : 1;
        Double finalGuidanceScale = (guidanceScale != null && guidanceScale >= 0 && guidanceScale <= 20) ? guidanceScale : 7.5;
        Integer finalNumInferenceSteps = (numInferenceSteps != null && numInferenceSteps >= 1 && numInferenceSteps <= 100) ? numInferenceSteps : 20;

        SiliconFlowImageRequest.Builder builder = SiliconFlowImageRequest.builder()
                .model("Kwai-Kolors/Kolors")
                .prompt(finalPrompt)
                .imageSize(finalImageSize)
                .batchSize(finalBatchSize)
                .guidanceScale(finalGuidanceScale)
                .numInferenceSteps(finalNumInferenceSteps);

        // 如果有参考图片，添加到请求中
        if (referenceImage != null && !referenceImage.isEmpty()) {
            builder.image(referenceImage);
        }

        return builder.build();
    }
}
